import React from 'react';
import {Table, Spin} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';
import {injectIntl} from './intl';
import style from './style.css';
import {gender, salesLeadIntentLevel, potentialCustomerMainDataSource, potentialCustomerStatus} from '../Enum';
import {conventEnumValueToString} from '../utils';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {abandonOrder} from './api';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false,
            selectedRowKeys: [],
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonOrder(id, record.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '潜客编号'
                }),
                dataIndex: 'code',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)}>{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.name',
                    defaultMessage: '客户姓名'
                }),
                dataIndex: 'name',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.gender',
                    defaultMessage: '性别'
                }),
                dataIndex: 'gender',
                render: text => conventEnumValueToString(gender, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.cellPhoneNumber',
                    defaultMessage: '客户电话'
                }),
                dataIndex: 'cellPhoneNumber',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.intentLevel',
                    defaultMessage: '意向级别'
                }),
                dataIndex: 'intentLevel',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'intentLevel' && this.props.sortedOrder,
                render: text => conventEnumValueToString(salesLeadIntentLevel, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.productCategoryCode',
                    defaultMessage: '意向车型'
                }),
                dataIndex: 'productCategoryCode',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.intentionalVehicle',
                    defaultMessage: '意向车辆'
                }),
                dataIndex: 'intentionalVehicle',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.mainDataSource',
                    defaultMessage: '主要来源'
                }),
                dataIndex: 'mainDataSource',
                render: text => conventEnumValueToString(potentialCustomerMainDataSource, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
                render: text => conventEnumValueToString(potentialCustomerStatus, text)
            }];
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operation',
                defaultMessage: '操作'
            }),
            dataIndex: 'id',
            key: 'id',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, r) => {
                const menus = [{
                    id: PERMISSION.abandon,
                    children: ref =>
                        <WrappedPopconfirm
                            id={r.id}
                            key="abandon"
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.popconfirm.message',
                                defaultMessage: '是否继续?'
                            })}
                            onVisibleChange={ref.setMenuVisible}
                            onConfirm={this.onAbandonBtn}>
                            <a key="abandon">
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.abandon',
                                    defaultMessage: '作废'
                                })}
                            </a>
                        </WrappedPopconfirm>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Spin spinning={this.props.loading || this.state.loading} className={style.spin}>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    locale={locale}
                    {...TABLE} />
            </Spin>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
